package com.greenhouse.protocol;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.greenhouse.protocol.common.enums.ProtocolEnum;
import com.greenhouse.protocol.properties.InitBean;

/**
 * 自动化配置初始化服务
 *
 **/
@Configuration
public class ServerAutoConfigure {

	private static final int _BLACKLOG = 1024;

	private static final int CPU = Runtime.getRuntime().availableProcessors();

	private static final int SEDU_DAY = 10;

	private static final int TIMEOUT = 120;

	private static final int BUF_SIZE = 10 * 1024 * 1024;

	private InitBean serverBean;

	public ServerAutoConfigure(InitBean serverBean) {
		this.serverBean = serverBean;
	}

	@Bean(initMethod = "open", destroyMethod = "close")
	public InitServer initServer() {
		if (!ObjectUtils.allNotNull(serverBean.getPort(), serverBean.getServerName())) {
			throw new NullPointerException("not set port");
		}
		if (serverBean.getBacklog() < 1) {
			serverBean.setBacklog(_BLACKLOG);
		}
		if (serverBean.getBossThread() < 1) {
			serverBean.setBossThread(CPU);
		}
		if (serverBean.getInitalDelay() < 0) {
			serverBean.setInitalDelay(SEDU_DAY);
		}
		if (serverBean.getPeriod() < 1) {
			serverBean.setPeriod(SEDU_DAY);
		}
		if (serverBean.getHeart() < 1) {
			serverBean.setHeart(TIMEOUT);
		}
		if (serverBean.getRevbuf() < 1) {
			serverBean.setRevbuf(BUF_SIZE);
		}
		if (serverBean.getWorkThread() < 1) {
			serverBean.setWorkThread(CPU * 2);
		}
		if (serverBean.getProtocol() == null) {
			serverBean.setProtocol(ProtocolEnum.MQTT);
		}
		return new InitServer(serverBean);
	}

}
